import os
import random
import sys
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import threading
import pandas as pd
import time

from 获取单元信息 import get_unit_detail, open_account_palt_form, edit_creative, get_final_construct_edit_data
from 更改单元信息 import update_intelligent_expansion, update_device_price


class IntelligentExpansionGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("部分创意信息设置工具")
        self.root.geometry("1000x700")
        self.root.minsize(800, 600)
        self.root.configure(bg="#f5f6f8")

        # 设置样式
        self.style = ttk.Style()
        self.style.theme_use('clam')

        # 配置通用样式
        self.configure_styles()

        # 初始化变量
        self.file_path = tk.StringVar()
        self.log_callback = None
        self.unit_data = None
        self.account_id = ""

        # 创建主容器
        self.main_container = ttk.Frame(self.root, padding="20")
        self.main_container.pack(fill=tk.BOTH, expand=True)

        # 创建各个功能区域
        self.create_header()
        self.create_control_section()
        self.create_log_area()
        self.create_status_bar()

    def configure_styles(self):
        """配置所有自定义样式"""
        # 主题颜色：蓝色系
        self.primary_color = "#1a73e8"
        self.secondary_color = "#dadce0"
        self.success_color = "#34a853"
        self.warning_color = "#fbbc05"
        self.error_color = "#d93025"
        self.bg_color = "#f5f6f8"
        self.card_color = "#ffffff"
        self.text_color = "#202124"

        # 框架背景色
        self.style.configure('TFrame', background=self.bg_color)

        # 标签样式
        self.style.configure('Card.TFrame', background=self.card_color, borderwidth=1, relief='solid')
        self.style.configure('Header.TLabel', font=('Segoe UI', 16, 'bold'), background=self.bg_color)
        self.style.configure('Section.TLabel', font=('Segoe UI', 13, 'bold'), background=self.card_color)
        self.style.configure('Status.TLabel', font=('Segoe UI', 11))
        self.style.configure('Description.TLabel', font=('Segoe UI', 11), background=self.card_color)
        self.style.configure('InputLabel.TLabel', font=('Segoe UI', 11), background=self.card_color, padding=(0, 0, 10, 0))

        # 输入控件样式
        self.style.configure('TLabel', background=self.card_color, font=('Segoe UI', 11), padding=5)
        self.style.configure('TEntry', font=('Segoe UI', 11), padding=8, borderwidth=1, relief='solid')
        self.style.configure('TButton', font=('Segoe UI', 11, 'bold'), padding=6, borderwidth=0, foreground='white')

        # 按钮样式
        self.style.configure('Primary.TButton', background=self.primary_color)
        self.style.map('Primary.TButton',
                       background=[('active', '#1557b0'), ('!active', self.primary_color)])

        self.style.configure('Danger.TButton', background=self.error_color)
        self.style.map('Danger.TButton',
                       background=[('active', '#b31b1b'), ('!active', self.error_color)])

        self.style.configure('Success.TButton', background=self.success_color)
        self.style.map('Success.TButton',
                       background=[('active', '#1f7a3a'), ('!active', self.success_color)])

        # 进度条样式
        self.style.configure("Horizontal.TProgressbar",
                             troughcolor=self.secondary_color,
                             background=self.primary_color,
                             thickness=15)

    def create_header(self):
        """创建标题栏"""
        header_frame = ttk.Frame(self.main_container)
        header_frame.pack(fill=tk.X, pady=(0, 15))

        ttk.Label(header_frame, text="部分创意信息设置工具", style='Header.TLabel').pack(side=tk.LEFT)

        # 版本标签（可选）
        version_label = ttk.Label(header_frame, text="v1.0", style='Status.TLabel', foreground=self.secondary_color)
        version_label.pack(side=tk.RIGHT)

    def create_control_section(self):
        """创建控制区域（账号和文件选择）"""
        control_card = ttk.Frame(self.main_container, style='Card.TFrame')
        control_card.pack(fill=tk.X, pady=(0, 20))

        # 主内容框架
        content_frame = ttk.Frame(control_card, padding="15")
        content_frame.pack(fill=tk.X, padx=10, pady=10)

        # 账号输入区域
        account_frame = ttk.Frame(content_frame)
        account_frame.pack(fill=tk.X, pady=(0, 8))

        ttk.Label(account_frame, text="子账号ID:", style='InputLabel.TLabel').pack(side=tk.LEFT, padx=(0, 5))

        self.account_entry = ttk.Entry(account_frame, width=30)
        self.account_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))

        ttk.Label(account_frame, text="输入需要操作的子账号ID", style='Description.TLabel', foreground="#505050").pack(side=tk.LEFT)

        # 文件选择区域
        file_frame = ttk.Frame(content_frame)
        file_frame.pack(fill=tk.X, pady=(0, 10))

        # 文件选择标签和按钮
        file_select_frame = ttk.Frame(file_frame)
        file_select_frame.pack(fill=tk.X)

        ttk.Label(file_select_frame, text="Excel文件:", style='InputLabel.TLabel').pack(side=tk.LEFT, padx=(0, 5))

        self.select_button = ttk.Button(file_select_frame, text="选择文件", command=self.select_file, style='Primary.TButton', width=8)
        self.select_button.pack(side=tk.RIGHT, padx=(0, 10))

        self.temp_button = ttk.Button(file_select_frame, text="模板文件", command=lambda: self.open_template_file(template_name='部分创意信息修改.xlsx'), style='Primary.TButton', width=8)
        self.temp_button.pack(side=tk.RIGHT, padx=(0, 10))

        self.file_path_label = ttk.Label(file_select_frame, textvariable=self.file_path, style='Status.TLabel', foreground="#505050", wraplength=500, anchor='w')
        self.file_path_label.pack(side=tk.LEFT, fill=tk.X, expand=True)

        # 单独一行的开始执行按钮
        execute_frame = ttk.Frame(content_frame)
        execute_frame.pack(fill=tk.X)

        self.start_button = ttk.Button(execute_frame, text="▶ 开始执行", command=self.start_task, style='Success.TButton', width=15)
        self.start_button.pack(pady=(5, 0))

    def create_log_area(self):
        """创建日志区域"""
        log_card = ttk.Frame(self.main_container, style='Card.TFrame')
        log_card.pack(fill=tk.BOTH, expand=True)

        header_frame = ttk.Frame(log_card)
        header_frame.pack(fill=tk.X, padx=15, pady=(10, 5))

        ttk.Label(header_frame, text="操作日志", style='Section.TLabel').pack(side=tk.LEFT)
        # ttk.Label(header_frame, text="显示程序运行时的详细信息", style='Description.TLabel', foreground="#505050").pack(side=tk.LEFT, padx=(10, 0))

        log_content = ttk.Frame(log_card)
        log_content.pack(fill=tk.BOTH, expand=True, padx=15, pady=(0, 15))

        # 日志文本区域
        self.log_text = tk.Text(log_content, wrap=tk.WORD, bg='white', height=20,
                                font=('Segoe UI', 10), bd=0, highlightthickness=0)
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.log_text.config(state=tk.DISABLED)

        # 滚动条
        scrollbar = ttk.Scrollbar(log_content, orient="vertical", command=self.log_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.log_text.config(yscrollcommand=scrollbar.set)

        # 进度条
        self.progress_bar = ttk.Progressbar(log_card, orient="horizontal", length=200, mode="determinate",
                                            style="Horizontal.TProgressbar")
        self.progress_bar.pack(fill=tk.X, padx=20, pady=10)

    def open_template_file(self, template_name='部分创意信息修改.xlsx'):
        """点击按钮后打开模板 Excel 文件"""
        # 构建模板路径
        if getattr(sys, 'frozen', False):  # 如果是打包后的程序
            base_path = sys._MEIPASS
            full_path = os.path.join(base_path, "shared", template_name)
        else:  # 开发环境
            full_path = os.path.abspath(os.path.join("..", "shared", template_name))

        # 检查文件是否存在
        if not os.path.exists(full_path):
            self.log_message(f"错误: 未找到模板文件 {full_path}", "red")
            return

        # 使用默认程序打开 Excel 文件
        try:
            if os.name == 'nt':  # Windows
                os.startfile(full_path)
            else:  # macOS / Linux
                import subprocess
                if sys.platform == 'darwin':
                    subprocess.call(['open', full_path])  # macOS
                else:
                    subprocess.call(['xdg-open', full_path])  # Linux
        except Exception as e:
            self.log_message(f"❌ 打开模板文件失败: {str(e)}", "red")

    def create_status_bar(self):
        """创建状态栏"""
        self.status_frame = ttk.Frame(self.root, style='Card.TFrame')
        self.status_frame.pack(fill=tk.X)

        self.status_label = ttk.Label(self.status_frame, text="就绪", style='Status.TLabel', foreground="green")
        self.status_label.pack(side=tk.LEFT, padx=20, pady=10)

    def select_file(self):
        file_path = filedialog.askopenfilename(title="选择Excel文件", filetypes=[("Excel 文件", "*.xlsx *.xls")])
        if file_path:
            self.file_path.set(file_path)
            self.status_label.config(text="✅ 文件已选择", foreground="green")

    def start_task(self):
        file_path = self.file_path.get()
        if not file_path or not os.path.exists(file_path):
            messagebox.showwarning("警告", "请先选择有效的Excel文件")
            return

        try:
            self.account_id = self.account_entry.get().strip()
            if not self.account_id:
                self.log_message("请输入账号ID！", "red")
                self.status_label.config(text="需要账号ID", foreground="red")
                return

            df = pd.read_excel(file_path)

            if '创意ID' not in df.columns:
                self.log_message(f"⚠️ 创意ID不能为空", "red")
                return

            if '封面优选' in df.columns and '笔记/素材ID' not in df.columns:
                self.log_message(f"⚠️ 需要更改封面优选时，表格中必须存在笔记ID列", "red")
                return

            unit_ids = df['创意ID'].astype(int).tolist()

            mask_fills = None
            note_id = None
            comp_loc = None
            comment = None
            search_word = None
            creative_name = None

            if '创意名称' in df.columns:
                creative_name = df['创意名称'].fillna('').astype(str).tolist()

            if '封面优选' in df.columns:
                mask_fills = df['封面优选'].apply(lambda x: x if pd.notna(x) else None).tolist()

            if '笔记/素材ID' in df.columns:
                note_id = df['笔记/素材ID'].apply(lambda x: x if pd.notna(x) else None).tolist()

            if '组件位置' in df.columns:
                comp_loc = df['组件位置'].apply(lambda x: str(x).strip().split('\n') if pd.notna(x) else []).tolist()

            if '置顶评论文案' in df.columns:
                comment = df['置顶评论文案'].astype(str).tolist()

            if '搜索词' in df.columns:
                search_word = df['搜索词'].astype(str).tolist()

            self.unit_data = list(zip(unit_ids, creative_name, mask_fills, comp_loc, comment, search_word, note_id))

            self.status_label.config(text="🔄 正在处理...", foreground="orange")
            self.progress_bar['value'] = 0
            self.progress_bar['maximum'] = len(self.unit_data)

            thread = threading.Thread(target=self.process_units, daemon=True)
            thread.start()

        except Exception as e:
            messagebox.showerror("错误", f"读取Excel失败: {str(e)}")
            self.status_label.config(text="❌ 数据加载失败", foreground="red")

    def process_units(self):
        self.log_message(f"⚠️ 正在打开合作伙伴平台", "green")
        unit_dict_cookie = open_account_palt_form(self.account_id)

        num_count = len(self.unit_data)
        index = 0

        for creative_id, creative_name, mask_fill_status, comp_loc, comment, search_word, note_id in self.unit_data:
            index += 1
            progress_percent = (index / num_count) * 100
            self.progress_bar['value'] = index
            self.status_label.config(text=f"处理中... {progress_percent:.1f}% 完成", foreground="orange")

            try:
                # 更新封面优选
                if pd.notna(mask_fill_status):
                    self.log_message(f"🔧 正在处理创意ID: {creative_id}, 将封面优选更改状态为: {mask_fill_status}... ", "blue")
                    raw_data = get_final_construct_edit_data(creative_id, self.account_id, unit_dict_cookie, note_id, mask_fill_status)
                    response = edit_creative(raw_data, self.account_id, unit_dict_cookie)
                    if response.get('code') == 0:
                        self.log_message(f"🔧 创意ID: {creative_id}, 更改状态成功... ", "green")
                    else:
                        fail_msg = response.get('msg', {})
                        self.log_message(f"🔧 创意ID: {creative_id}, 更改状态失败-失败原因:{fail_msg} ", "red")

                    time.sleep(random.randint(1, 3))

                # 修改创意名称
                if pd.notna(creative_name) and creative_name:
                    self.log_message(f"🔧 正在处理创意ID: {creative_id}, 将创意名称修改为: {creative_name}... ", "blue")
                    raw_data = get_final_construct_edit_data(creative_id, self.account_id, unit_dict_cookie, note_id, mask_fill_status)
                    raw_data['creativityName'] = creative_name
                    response = edit_creative(raw_data, self.account_id, unit_dict_cookie)
                    if response.get('code') == 0:
                        self.log_message(f"🔧 创意ID: {creative_id}, 更改创意名称成功... ", "green")
                    else:
                        fail_msg = response.get('msg', {})
                        self.log_message(f"🔧 创意ID: {creative_id}, 更改创意名称失败-失败原因:{fail_msg} ", "red")

                    time.sleep(random.randint(1, 3))

                # 修改搜索组件
                if comp_loc:
                    comp_loc = str(comp_loc).strip()  # 强制转为字符串并去除空格
                    if len(comp_loc) > 0:
                        self.log_message(f"🔧 正在处理创意ID: {creative_id}, 修改搜索组件... ", "blue")
                        raw_data = get_final_construct_edit_data(creative_id, self.account_id, unit_dict_cookie, note_id, mask_fill_status)
                        if '图片或视频底部' in comp_loc and '置顶评论' in comp_loc:
                            raw_data['conversionComponentTypes'] = [0, 1]
                            raw_data['barContent'] = search_word
                            raw_data['comment'] = comment
                            raw_data['commentUserList'] = [comment]

                        if '图片或视频底部' in comp_loc and '置顶评论' not in comp_loc:
                            raw_data['conversionComponentTypes'] = [0]
                            raw_data['barContent'] = search_word

                        if '图片或视频底部' not in comp_loc and '置顶评论' in comp_loc:
                            raw_data['conversionComponentTypes'] = [1]
                            raw_data['barContent'] = search_word
                            raw_data['comment'] = comment
                            raw_data['commentUserList'] = [comment]

                        response = edit_creative(raw_data, self.account_id, unit_dict_cookie)
                        if response.get('code') == 0:
                            self.log_message(f"🔧 创意ID: {creative_id}, 更改搜索组件成功... ", "green")
                        else:
                            fail_msg = response.get('msg', {})
                            self.log_message(f"🔧 创意ID: {creative_id}, 更改搜索组件失败-失败原因:{fail_msg} ", "red")
                        time.sleep(random.randint(1, 3))

            except Exception as e:
                error_msg = f"❌ 单元ID {creative_id} 出现异常: {str(e)}"
                self.log_message(error_msg, "red")
                time.sleep(3)

        self.status_label.config(text="✔️ 所有任务已完成", foreground="green")

    def result_status(self, result, unit_id, text_str=None):
        if result.get('code') == 200:
            self.log_message(f"✅ 创意ID {unit_id} - 提交成功 \n", "green")
        else:
            self.log_message(f"❌ 创意ID {unit_id} 提交失败: {result.get('msg', '未知错误')} \n", "red")

    def log_message(self, message, color="black"):
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, message + "\n", color)
        self.log_text.tag_config(color, foreground=color)
        self.log_text.config(state=tk.DISABLED)
        self.log_text.see(tk.END)